package edu.gatech.cc.hwa.server.security;

import java.util.Collection;

import edu.gatech.cc.hwa.server.AuthenticationParameters;
import edu.gatech.cc.hwa.server.Profile;
import edu.gatech.cc.hwa.server.User;
import edu.gatech.cc.hwa.server.database.Database;
import edu.gatech.cc.hwa.server.database.exceptions.DatabaseException;
import edu.gatech.cc.hwa.server.security.exceptions.HwaSecurityException;

public class Authenticator {

	public static boolean authenticate(AuthenticationParameters params) throws HwaSecurityException {
		User user = null;
		try {
			user = Database.getUser(params.getUserName());
			if (authenticatePassword(user, params)) {
				Collection<Profile> userProfiles = Database.getProfilesForUser(user);
				for(Profile profile : userProfiles) {
					if (profile.authenticateFeatures(params)) {
						profile.update(params);
						Database.updateProfile(profile);
						return true;
					}
				}
			}
			return false;
		} catch (DatabaseException e) {
			throw new HwaSecurityException(e);
		}
	}
	
	private static boolean authenticatePassword(User user, AuthenticationParameters params) throws HwaSecurityException {
		return user.getPasswordHash().equals(params.getHashedPassword());
	}
}
